package com.dubbo.windows;

import com.alibaba.fastjson.JSONObject;
import com.dubbo.util.*;
import javafx.application.Application;
import javafx.application.Platform;

import javafx.beans.value.ChangeListener;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import org.springframework.boot.origin.OriginTrackedValue;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.util.StopWatch;
import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;


public abstract class DubboForm extends Application {
    private static final String version= "1.2.8";
    private Map<String,String> cache=new HashMap<>();
    private DubboReferenceUtil dubboReferenceUtil;
    //private RegistryContainer registryContainer;
    private static Map<String,String> zookeeperCache=new HashMap<>();
    private ZookeeperUtil zookeeperUtil;
    private Environment env;
    private static final Logger LOG = Logger.getLogger("DubboForm");
    private static String exepath=System.getProperty("exe.path");
    private static String exeAddress=System.getProperty("exe4j.moduleName");
    static {
        zookeeperCache.put("dev","192.168.2.2:2181");
        zookeeperCache.put("sim","192.168.1.250:2181");
        zookeeperCache.put("pet","192.168.2.100:2181");
        zookeeperCache.put("sit","192.168.1.182:2181");
        zookeeperCache.put("uat","192.168.1.48:2181");
        zookeeperCache.put("pre","192.168.1.242:2181");
        zookeeperCache.put("vip","mse-ec869700-zk.mse.aliyuncs.com:2181");
        zookeeperCache.put("prod","mse-d0ccc1c3-zk.mse.aliyuncs.com:2181");
    }
    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("dubbo可视化调用工具 版本"+version);
        primaryStage.setResizable(true);
        primaryStage.getIcons().add(new Image(Objects.requireNonNull(DubboForm.class.getClassLoader().getResourceAsStream("images/favicon.jpg"))));
        primaryStage.setOnCloseRequest(event -> {
            List<String> data=new ArrayList<>();
            for(Map.Entry<String,String> entry:cache.entrySet()){
                String interfaceMethod=entry.getKey();
                String param=entry.getValue();
                JSONObject jsonObject=JSONObject.parseObject(param);
                jsonObject.put("interfaceMethod",interfaceMethod);
                data.add(jsonObject.toJSONString());
                FileReadWriteUtil.writeFileMap(exepath+"dubbo参数字典.txt",data);
            }
            System.exit(0);
        });
         //Platform.setImplicitExit(false);
        BufferedImage image = ImageIO.read(Objects.requireNonNull(DubboForm.class.getClassLoader().getResourceAsStream("images/favicon.jpg")));
        TrayIcon trayIcon = new TrayIcon(image, "dubbo");
        trayIcon.setImageAutoSize(true);
        SystemTray tray = SystemTray.getSystemTray();
        trayIcon.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
                    Platform.runLater(() -> {
                        if (primaryStage.isIconified()) {
                            primaryStage.setIconified(false);
                        }
                        if (!primaryStage.isShowing()) {
                            primaryStage.show();
                        }
                        primaryStage.toFront();
                    });
                }
                else if (e.getButton() == MouseEvent.BUTTON3) {
                    Platform.setImplicitExit(true);
                    tray.remove(trayIcon);
                    Platform.runLater(primaryStage::close);
                    List<String> data=new ArrayList<>();
                    for(Map.Entry<String,String> entry:cache.entrySet()){
                        String interfaceMethod=entry.getKey();
                        String param=entry.getValue();
                        JSONObject jsonObject=JSONObject.parseObject(param);
                        jsonObject.put("interfaceMethod",interfaceMethod);
                        data.add(jsonObject.toJSONString());
                        FileReadWriteUtil.writeFileMap(exepath+"dubbo参数字典.txt",data);
                    }
                    System.exit(0);
                }
            }
        });
        tray.add(trayIcon);

        List<String> res= FileReadWriteUtil.readFileString(exepath+"dubbo参数字典.txt");
        if(res!=null&&res.size()>0) {
            for (String json : res) {
                JSONObject jsonObject = JSONObject.parseObject(json);
                String interfaceMethod = jsonObject.getString("interfaceMethod");
                jsonObject.remove("interfaceMethod");
                cache.put(interfaceMethod, jsonObject.toJSONString());
            }
        }
        GridPane grid = new GridPane();
        grid.setAlignment(Pos.CENTER);
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(25, 25, 25, 25));

        Text scenetitle = new Text("dubbo 配置参数设置");
        scenetitle.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20));
        grid.add(scenetitle, 0, 0, 2, 1);

        Label zookeeper = new Label("注册中心服务器地址(默认sim环境):");
        grid.add(zookeeper, 0, 1);
        /*TextField zookeeperAddress = new TextField();
        grid.add(zookeeperAddress, 1, 1,2,1);*/

        ComboBox zookeeperAddress=new ComboBox(FXCollections.observableArrayList(Arrays.asList(new String[]{"dev","sim","pet","sit","uat","pre","vip"})));
        zookeeperAddress.setPrefWidth(400);
        zookeeperAddress.setEditable(true);
        zookeeperAddress.getSelectionModel().select(1);
        grid.add(zookeeperAddress, 1, 1,2,1);

        Label timeout = new Label("远程服务调用超时时间(毫秒)(默认5000):");
        grid.add(timeout, 0, 2);
        TextField timeoutValue = new TextField();
        grid.add(timeoutValue, 1, 2,2,1);

        Label directAddress = new Label("远程服务调用直连地址(非必填):");
        grid.add(directAddress, 0, 3);
        TextField directAddressValue = new TextField();
        grid.add(directAddressValue, 1, 3,2,1);

        Button btn = new Button("设 置");
        HBox hbBtn = new HBox(10);
        hbBtn.setAlignment(Pos.BOTTOM_RIGHT);
        hbBtn.getChildren().add(btn);
        grid.add(hbBtn, 2, 4);

        btn.setOnAction(e -> {
            String zookAddressTemp=zookeeperAddress.getValue().toString();
            String zookAddress=zookAddressTemp;
            if(zookeeperCache.containsKey(zookAddressTemp)){
                zookAddress=zookeeperCache.get(zookAddressTemp);
                if("sit".equals(zookAddressTemp)||"prod".equals(zookAddressTemp)||"vip".equals(zookAddressTemp)){
                    SSHUtil.initDB(zookAddress.split(":")[0],Integer.valueOf(zookAddress.split(":")[1]));
                    zookAddress="127.0.0.1:2180";
                }
            }
            if(StringUtils.isEmpty(zookAddress)){
                ZookeeperUtil.setZkHost("192.168.1.250:2181");
            }else{
                ZookeeperUtil.setZkHost(zookAddress);
            }
            DubboReferenceUtil.zookeeperAddress=StringUtils.isEmpty(zookAddress)?"zookeeper://192.168.1.250:2181":"zookeeper://"+zookAddress;
            DubboReferenceUtil.registryTimeout= StringUtils.isEmpty(timeoutValue.getText())?5000:Integer.valueOf(timeoutValue.getText());
            DubboReferenceUtil.directAddress=directAddressValue.getText();

            env=SpringContextUtil.getBean(Environment.class);
            ConfigurableEnvironment  configurableEnvironment= (ConfigurableEnvironment) env;
            MutablePropertySources mutablePropertySources=configurableEnvironment.getPropertySources();
            for (PropertySource<?> propertySource : mutablePropertySources) {
                boolean applicationConfig = propertySource.getName().contains("applicationConfig");
                if (!applicationConfig) {
                    continue;
                }
                Map<String, OriginTrackedValue> source = (Map<String, OriginTrackedValue>) propertySource.getSource();
                OriginTrackedValue originTrackedValue = source.get("dubbo.registry.address");
                OriginTrackedValue newOriginTrackedValue = OriginTrackedValue.of(DubboReferenceUtil.zookeeperAddress, originTrackedValue.getOrigin());
                OriginTrackedValue originTrackedValue1 = source.get("dubbo.consumer.timeout");
                OriginTrackedValue newOriginTrackedValue1 = OriginTrackedValue.of(DubboReferenceUtil.registryTimeout, originTrackedValue1.getOrigin());
                source.put("dubbo.registry.address", newOriginTrackedValue);
                source.put("dubbo.consumer.timeout",newOriginTrackedValue1);

                OriginTrackedValue originTrackedValue2 = source.get("dubbo.consumer.directAddress");
                if(originTrackedValue2!=null&&DubboReferenceUtil.directAddress!=null&&!"".equals(DubboReferenceUtil.directAddress)) {
                    OriginTrackedValue newOriginTrackedValue2 = OriginTrackedValue.of(DubboReferenceUtil.directAddress, originTrackedValue2.getOrigin());
                    source.put("dubbo.consumer.directAddress", newOriginTrackedValue2);
                }
                LOG.info("环境属性:"+source);
            }
            dubboReferenceUtil= SpringContextUtil.getBean(DubboReferenceUtil.class);
            //registryContainer=SpringContextUtil.getBean(RegistryContainer.class);
            zookeeperUtil=SpringContextUtil.getBean(ZookeeperUtil.class);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException interruptedException) {
                interruptedException.printStackTrace();
            }
            primaryStage.setTitle("dubbo请求参数设置"+version);
            primaryStage.setScene(createMainScene(primaryStage));
                });
        Scene scene = new Scene(grid, 400, 275);
        primaryStage.setScene(scene);
        primaryStage.show();
        new Thread(()->{
            checkVersion(primaryStage);
       }).start();
    }

    private Scene createMainScene(Stage primaryStage){
        ScrollPane scrollPane=new ScrollPane();
        scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        Scene scene = new Scene(scrollPane, 780, 750);
        GridPane grid = new GridPane();
        grid.setMinSize(100,100);
        grid.setAlignment(Pos.TOP_LEFT);
        grid.setHgap(5);
        grid.setVgap(5);
        grid.setPadding(new Insets(10, 10, 10, 10));

        Text scenetitleTemp = new Text("dubbo 请求参数配置");
        scenetitleTemp.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20));
        grid.add(scenetitleTemp, 0, 0, 1, 1);

        Button btnClear = new Button("清空参数(重新拉取zookeeper信息)");
        btnClear.setPrefWidth(250);
        HBox hbBtnClear = new HBox(100);
        hbBtnClear.setAlignment(Pos.BOTTOM_RIGHT);
        hbBtnClear.setPrefWidth(250);
        hbBtnClear.getChildren().add(btnClear);
        grid.add(hbBtnClear, 2, 0,3,1);

        Label className = new Label("接口名称:");
        className.setPrefWidth(300);
        grid.add(className, 0, 1,1,1);
        ComboBox classNameField=new ComboBox(FXCollections.observableArrayList(zookeeperUtil.getRpcInterfaces()));
        classNameField.setPrefWidth(400);
        classNameField.setEditable(true);

        ComboBox methodNameField=new ComboBox();
        methodNameField.setPrefWidth(400);

        ChangeListener<String> listener=  (observable, oldValue,newValue) -> {
                Set<String> tempRpcInyerfaces = new HashSet<>();
                for (String rpcInterface : zookeeperUtil.getRpcInterfaces()) {
                    if (rpcInterface.toLowerCase().contains(newValue.toLowerCase())) {
                        tempRpcInyerfaces.add(rpcInterface);
                    }
                }
                classNameField.setItems(FXCollections.observableArrayList(tempRpcInyerfaces));
                LOG.info("关键字有"+tempRpcInyerfaces.size()+"个匹配的接口");
                LOG.info("匹配的接口："+JSONObject.toJSONString(tempRpcInyerfaces));
        };
        classNameField.getEditor().textProperty().addListener(listener);

        ComboBox addressField=new ComboBox();
        addressField.setPrefWidth(400);
        classNameField.setOnAction(event -> {
            String value = classNameField.getEditor().getText();
            classNameField.setItems(FXCollections.observableArrayList(zookeeperUtil.getRpcInterfaces()));
            Set<String> methodNames = zookeeperUtil.getRpcMethods(value);
            if(methodNames!=null) {
                methodNameField.setItems(FXCollections.observableArrayList(methodNames));
            }
            methodNameField.getSelectionModel().select(0);

            Set<String> addressSet=zookeeperUtil.getRpcAddress(value);
            if(addressSet!=null) {
                addressField.setItems(FXCollections.observableArrayList(addressSet));
            }
        });
        btnClear.setOnAction(e -> {
            zookeeperUtil.init();
            primaryStage.setScene(createMainScene(primaryStage));
        });
        grid.add(classNameField, 2, 1,3,1);

        Label methodName = new Label("方法名称:");
        methodName.setPrefWidth(300);
        grid.add(methodName, 0, 2,1,1);


        grid.add(methodNameField, 2, 2,3,1);


        Label isThereParameter = new Label("是否有参数:");
        isThereParameter.setPrefWidth(300);
        grid.add(isThereParameter, 0, 3,1,1);
        String[] s = {"有参","无参"};
        ComboBox isThereParameterField=new ComboBox(FXCollections.observableArrayList(Arrays.asList(s)));
        isThereParameterField.setPrefWidth(400);
        isThereParameterField.getSelectionModel().select(0);
        grid.add(isThereParameterField, 2, 3,3,1);

        Label address = new Label("直连地址:");
        address.setPrefWidth(300);
        grid.add(address, 0, 4,1,1);

        grid.add(addressField, 2, 4,3,1);


        Label requestTime = new Label("请求耗时(毫秒):");
        requestTime.setPrefWidth(300);
        grid.add(requestTime, 0, 5,1,1);



        TextField requestTimeField=new TextField();
        requestTimeField.setPrefWidth(300);
        requestTimeField.setEditable(false);
        grid.add(requestTimeField, 2, 5,3,1);


        TextArea textAreaJSON=new TextArea();
        textAreaJSON.setPrefRowCount(3);
        textAreaJSON.setPrefColumnCount(4);
        textAreaJSON.setEditable(true);
        grid.add(textAreaJSON, 0, 6,4,3);
        TextArea textAreaResponse=new TextArea();
        List<Map<String,TextField>> reQueryList=new ArrayList<>();
        final AtomicInteger index=new AtomicInteger(17);
        TextField keyField = new TextField();
        TextField valueField = new TextField();
        methodNameField.setOnAction(event -> {
            textAreaResponse.setText("");
            keyField.setText("");
            valueField.setText("");
            int tempIndex;
           while((tempIndex= (index.get()-17))>0) {
               index.decrementAndGet();
               Map<String, TextField> tempMap = reQueryList.get(tempIndex - 1);
               for (TextField textField : tempMap.values()) {
                   grid.getChildren().remove(textField);
               }
               reQueryList.remove(tempMap);
           }


           String clz = classNameField.getValue().toString();
            String method = methodNameField.getValue().toString();
            String interfaceMethod=clz+"-"+method;
            String param=cache.get(interfaceMethod);
            if(param!=null) {
                textAreaJSON.setText(param);
                Map<String,Object> m=JSONObject.parseObject(param);
                int i=0;
                for(Map.Entry<String,Object> entry:m.entrySet()){
                    String key = entry.getKey();
                    String value =  entry.getValue().toString();

                    if(i==0){
                        keyField.setText(key);
                        valueField.setText(value);
                    }else {
                        Map<String, TextField> reQuery = new HashMap<>();
                        TextField keyFieldTemp = new TextField();
                        keyFieldTemp.setPrefWidth(350);
                        keyFieldTemp.setText(key);
                        grid.add(keyFieldTemp, 0, index.get(), 2, 1);
                        reQuery.put("key", keyFieldTemp);

                        TextField valueFieldTemp = new TextField();
                        valueFieldTemp.setPrefWidth(350);
                        valueFieldTemp.setText(value);
                        grid.add(valueFieldTemp, 3, index.get(), 2, 1);
                        reQuery.put("value", valueFieldTemp);

                        index.incrementAndGet();
                        reQueryList.add(reQuery);
                    }
                    i++;
                }
            }else{
                textAreaJSON.setText("");
            }
        });


        Button btnTransfer = new Button("发送请求");
        btnTransfer.setPrefWidth(750);
        HBox hbBtnTransfer = new HBox(100);
        hbBtnTransfer.setAlignment(Pos.BOTTOM_CENTER);
        hbBtnTransfer.setPrefWidth(750);
        hbBtnTransfer.getChildren().add(btnTransfer);
        grid.add(hbBtnTransfer, 0, 9,4,1);

        //TextArea textAreaResponse=new TextArea();
        textAreaResponse.setPrefColumnCount(4);
        textAreaResponse.setEditable(false);
        grid.add(textAreaResponse, 0, 10,4,4);

        Button btnQuery = new Button("添加请求参数");
        HBox hbBtnQuery = new HBox(10);
        hbBtnQuery.setAlignment(Pos.BOTTOM_LEFT);
        hbBtnQuery.getChildren().add(btnQuery);
        grid.add(hbBtnQuery, 0, 14,1,1);


        Button btnDel = new Button("删除请求参数");
        HBox hbBtnDel = new HBox(10);
        btnDel.setAlignment(Pos.BOTTOM_CENTER);
        hbBtnDel.getChildren().add(btnDel);
        grid.add(hbBtnDel, 2, 14,3,1);

        Label key = new Label("key");
        key.setPrefWidth(350);
        grid.add(key, 0, 15,2,1);
        Label value = new Label("value");
        value.setPrefWidth(350);
        grid.add(value, 3, 15,2,1);

        //TextField keyField = new TextField();
        keyField.setPrefWidth(350);
        grid.add(keyField, 0, 16,2,1);

        //TextField valueField = new TextField();
        valueField.setPrefWidth(350);
        grid.add(valueField, 3, 16,2,1);

        btnQuery.setOnAction(e -> {
            Map<String,TextField> reQuery=new HashMap<>();
            TextField keyFieldTemp = new TextField();
            keyFieldTemp.setPrefWidth(350);
            grid.add(keyFieldTemp, 0, index.get(),2,1);
            reQuery.put("key",keyFieldTemp);

            TextField valueFieldTemp = new TextField();
            valueFieldTemp.setPrefWidth(350);
            grid.add(valueFieldTemp, 3, index.get(),2,1);
            reQuery.put("value",valueFieldTemp);

            index.incrementAndGet();
            reQueryList.add(reQuery);
        });

        btnDel.setOnAction(e->{
            int tempIndex= index.get()-17;
            if(tempIndex==0){
                keyField.setText("");
                valueField.setText("");
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("dubbo返回");
                alert.setHeaderText(null);
                alert.setContentText("我是有底线的!!!");
                alert.showAndWait();
                return;
            }
            index.decrementAndGet();
            Map<String,TextField> tempMap=reQueryList.get(tempIndex-1);
            for(TextField textField: tempMap.values()){
                grid.getChildren().remove(textField);
            }
            reQueryList.remove(tempMap);
        });


        btnTransfer.setOnAction(e->{
                textAreaResponse.clear();
                String jsonRequest = textAreaJSON.getText();
                String clz = classNameField.getValue().toString();
                String method = methodNameField.getValue().toString();
                String isThereParameterValue=isThereParameterField.getValue().toString();
                boolean isParameter="有参".equals(isThereParameterValue);
                String inerfaceMethod=clz+"-"+method;
                 Object addressObj=  addressField.getValue();
                 String temp=clz;
                 String directAddress="";
                 if(addressObj!=null) {
                     directAddress = addressObj.toString();
                     temp=directAddress+"_directaddress_"+clz;
                 }
                 String classname=temp;
                JSONObject param = new JSONObject();
                if(!StringUtils.isEmpty(keyField.getText())) {
                    param.put(keyField.getText(), valueField.getText());
                }
                for (Map<String, TextField> map : reQueryList) {
                    String keyText=map.get("key").getText();
                    if(!StringUtils.isEmpty(keyText)) {
                        param.put(keyText, map.get("value").getText());
                    }
                }
                if(param.size()<=0) {
                    if (jsonRequest != null && jsonRequest.length() > 0) {
                        param = JSONObject.parseObject(jsonRequest);
                    }
                }
                if(param!=null&&param.size()>0) {
                    textAreaJSON.setText(JSONObject.toJSONString(param));
                }
                JSONObject finalParam = param;
                if(finalParam.size()>0) {
                    cache.put(inerfaceMethod, JSONObject.toJSONString(finalParam));
                }
                Thread thread=new Thread(()->{
                    try {
                        StopWatch stopWatch = new StopWatch();
                        stopWatch.start("rpc调用");
                        Object zlRpcResult = dubboReferenceUtil.invokeMethod(classname, method, finalParam,isParameter);
                        LOG.info("rpc调用结果:" + JSONObject.toJSONString(zlRpcResult));
                        stopWatch.stop();
                        LOG.info(stopWatch.prettyPrint());
                        Platform.runLater(()->{
                            requestTimeField.setText(stopWatch.getTotalTimeMillis()+"ms");
                            textAreaResponse.appendText(JsonFormatTool.formatJson(JSONObject.toJSONString(zlRpcResult)));
                        });
                    }catch (Exception ex){
                        ex.printStackTrace();
                        textAreaResponse.appendText(printThrowable(ex));
                    }
                });
               thread.start();
         });

        scrollPane.setContent(grid);
        return scene;
    }

    private  String printThrowable(Throwable e){
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        e.printStackTrace(pw);
        pw.flush();
        sw.flush();
        return sw.toString();
    }
    private void checkVersion(Stage primaryStage){
        String newVersion=getVersion();
        if(!isNewVersion(version,newVersion)){
            Platform.runLater(() -> {
                Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
                alert.setTitle("版本更新");
                alert.setHeaderText("当前版本号"+version+",最新版本号"+newVersion+",建议您更新程序");
                alert.setContentText("是否更新?");
                Optional<ButtonType> result = alert.showAndWait();
                if (result.get() == ButtonType.OK){
                    Group root = new Group();
                    Scene scene = new Scene(root, 220, 50);
                    primaryStage.setScene(scene);
                    primaryStage.setTitle("下载进度");
                    final Label label = new Label();
                    label.setText("进度:");
                    final ProgressBar pb = new ProgressBar();
                    final ProgressIndicator pin = new ProgressIndicator();
                    final HBox hb  = new HBox();
                    hb.setSpacing(1);
                    hb.setAlignment(Pos.CENTER);
                    hb.getChildren().addAll(label, pb, pin);
                    final VBox vb = new VBox();
                    vb.setSpacing(1);
                    vb.getChildren().add(hb);
                    scene.setRoot(vb);
                    primaryStage.show();
                    downloadYapi(pb,pin,version,newVersion);
                } else {
                    // ... user chose CANCEL or closed the dialog
                }
            });
        }

    }

    private boolean isNewVersion(String version,String newVersion){
        String[] versions=version.split("\\.");
        String[] newVersions=newVersion.split("\\.");
        int length=versions.length;
        int lengthV=newVersions.length;
        int minLength=Math.min(length,lengthV);
        for(int i=0;i<minLength;i++){
            int o=Integer.valueOf(versions[i]);
            int n=Integer.valueOf(newVersions[i]);
            if(o<n){
                return false;
            }
            if(o>n){
                return true;
            }
        }
        return length>=lengthV?true:false;
    }
    public static String getVersion(){
        try {
            String res = OkHttpUtil.post("http://120.92.153.28:8080/gitlog/dubbo/version", "", null);
            LOG.info("版本信息 " + res);
            JSONObject jsonObject = JSONObject.parseObject(res);
            String newVersion = jsonObject.getString("data");
            return newVersion;
        }catch (Exception e){
            e.printStackTrace();
            return "0";
        }
    }
    public static void downloadYapi(ProgressBar pb, ProgressIndicator pin,String version, String newVersion){
        String downLoad=System.getProperty("user.dir");
        String fileName="dubbo-"+newVersion+".exe";
        //String oldFileName="dubbo-"+version+".exe";
        LOG.info("当前下载路径:"+downLoad+"文件名:"+fileName +"exe路径:"+exepath);
        OkHttpUtil.download("http://120.92.153.28:8080/gitlog/dubbo/downLoad",downLoad,fileName,new OkHttpUtil.OnDownloadListener(){

            @Override
            public void onDownloadSuccess(File file) {
                Thread thread =new Thread(()->{
                    try {
                        Runtime.getRuntime().exec(downLoad+"\\"+fileName+" "+exeAddress);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    System.exit(0);
                });
                thread.start();
            }

            @Override
            public void onDownloading(int progress) {
                Platform.runLater(() -> {
                    pb.setProgress(progress/100d);
                    pin.setProgress(progress/100d);
                });
            }

            @Override
            public void onDownloadFailed(Exception e) {
                Platform.runLater(() -> {
                    Alert alert = new Alert(Alert.AlertType.ERROR);
                    alert.setTitle("异常");
                    alert.setHeaderText("下载错误");
                    alert.setContentText("下载出错!");
                });
            }
        });
    }
}
